import _ from "lodash";
import { io, Socket } from "socket.io-client";
import {SocketIoChannel} from '@common/constants.ts'
import { useImageDataStore } from "@renderer/store/pinia/imageData";
class BaseSocketIo {
  ioInstance: Socket;
  uri;

  constructor(
    uri,
    opts = {
      transports: ['websocket'],
      upgrade: false,
      rememberUpgrade: false,
      forceNew: true,
      autoConnect: true, // 自动连接
    },
  ) {
    this.uri = uri;
    this.ioInstance = io(uri, opts);
    this.listenConnectEvents();
  }

  connect(): void {
    this.ioInstance.connect();
  }

  listenConnectEvents(): void {
    this.ioInstance.on("connect", () => {
      console.log(`${this.uri},socket io connected`);
    });

    this.ioInstance.on("disconnect", () => {
      console.log(`${this.uri},socket io disconnect`);
    });

    this.ioInstance.on(
      "connect_error",
      _.throttle((e) => {}, 60 * 1000),
    );
  }
}


 class ImageSocketIo extends BaseSocketIo {
  constructor() {

    const imageUri = `http://127.0.0.1:8080/ct`;
    super(imageUri);
    this.listenImageEvents();
  }

  listenImageEvents(): void {
    this.ioInstance.on(SocketIoChannel.Image, (data) => {
      const imageDataStore = useImageDataStore()
      imageDataStore.updateImageData(data)
    });
    this.ioInstance.on(SocketIoChannel.Connect, (data) => {
      console.log('scoketio connect');

    });
    this.ioInstance.on(SocketIoChannel.Disconnect, (data) => {
      console.log('scoketio disconnect');

    });
  }

  sendMsg(msg):void {
    this.ioInstance.send(msg)
  }
}

const imgSocketIo = new ImageSocketIo();

export default imgSocketIo;


